package com.example.haiti.infrastructure.surveyor;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

public class main_Activity extends ListActivity {
	
	public Context mContext;
    private ListView mainListView = null;
    CustomSqlCursorAdapter adapter = null;
    private Cursor currentCursor = null;
    private Utils utilsHelper = null;
    
    private int structureID;

    private ListView listView = null;
    
    private static final int STRUCTURE_ADD_DIALOG_ID = 0;
    private static final int STRUCTURE_EDIT_DIALOG_ID = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.structure_list_view);
        
        // Caputures application activity to the mContext variable
        mContext = this;
       
        // Creates the dbHelper object and opens the database
        utilsHelper = new Utils(mContext);        
             
        setupAddStructureButton();

       new SelectDataTask().execute();

       setupListView(); 

    } // end of the onCreate method
    
    private void setupListView(){  	
        listView = getListView();
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        this.mainListView = getListView();
        mainListView.setCacheColorHint(0);
        registerForContextMenu(getListView());
    }
    
    private  void setupAddStructureButton(){
        // Add structure button
        ImageButton btnAddStructure = (ImageButton) findViewById(R.id.btnAddStructure);
        btnAddStructure.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
            	showDialog(STRUCTURE_ADD_DIALOG_ID);           	                       	            
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        new SelectDataTask().execute();
    }

    @Override
    protected void onPause() {
        super.onPause();

        utilsHelper.closeDatabase();
    }
    
    @Override
    protected void onStop() {
      super.onStop();
       
    	utilsHelper.closeDatabase();
    }
    
    private class SelectDataTask extends AsyncTask<Void, Void, String> {
        
    	private ProgressDialog pdia;
        
    	@Override
        protected void onPreExecute(){ 
                pdia = new ProgressDialog(mContext);
                pdia.setMessage("Loading Structures ...");
                pdia.show();    
        }

        protected String doInBackground(Void... params) {

            try {
            
               utilsHelper.openDatabase();                	
               main_Activity.this.currentCursor = utilsHelper.dbHelper.getCursor(null);
               
            } catch (SQLException sqle) {

                throw sqle;

            }
            return null;
        }

        protected void onPostExecute(final String result) {

        	pdia.dismiss(); 
            startManagingCursor(main_Activity.this.currentCursor);
            int[] listFields = new int[] { R.id.structure_title };
            String[] dbColumns = new String[] { SqlHelper.COLUMN_STRUCTURE_NAME };

            main_Activity.this.adapter = new CustomSqlCursorAdapter(
                    main_Activity.this, R.layout.structure_item,
                    main_Activity.this.currentCursor, dbColumns, listFields,
                    utilsHelper.dbHelper);
            setListAdapter(main_Activity.this.adapter);            
        }
    }
    
    @Override 
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        
        structureID = (int)id;
        utilsHelper.startNextActivity(structureID, questionnaire_Activity1.class);

    }
    
    
    // A pop-up dialog is created to allow the user to create and edit a structure. 
    // REQ 3.3.4.R1 met
    @Override
    protected Dialog onCreateDialog(int id) {
		
            switch (id) {

            case STRUCTURE_ADD_DIALOG_ID:
        		                      		
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                   
                    // Inflates the custom xml file layout create_structure_dialog.xml
                    LayoutInflater inflater = this.getLayoutInflater();    
                    View  dialogView  =  inflater.inflate(R.layout.create_structure_dialog,null);
                    builder.setView(dialogView);
                    
                    builder.setTitle(R.string.structure_add_dialog_title);
                    //builder2.setIcon(R.drawable.icon);    
                    
                    final EditText Edit_structureNameNew = (EditText) dialogView.findViewById(R.id.editStructureName);     
            		final EditText Edit_structureDescNew = (EditText) dialogView.findViewById(R.id.editStructureDescription);
                    
                    builder.setPositiveButton(R.string.save,
                    		          
                                    new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                
                                            	// Defines strings input in by the user
                                                String structureName = Edit_structureNameNew.getText().toString();
                                                String structureDesc = Edit_structureDescNew.getText().toString();
                                            	
                                                // Adds the user-defined structure to  the database
                                                utilsHelper.dbHelper.createStructureEntry(structureName, structureDesc);
                                                
                                                // Refersehs the list  view screen with new changes                                              
                                                updateList();
                                                
                                                return;
                                            }
                                    });

                    builder.setNegativeButton(android.R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {                                                   
                                                    return;
                                            }
                                    });    
                    
                    Dialog structureDialog = builder.create();

                    return structureDialog;
                    
            case STRUCTURE_EDIT_DIALOG_ID:
          		
                AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
               
                // Inflates the custom xml file layout create_structure_dialog.xml
                LayoutInflater inflater2 = this.getLayoutInflater();    
                View  dialogView2  =  inflater2.inflate(R.layout.create_structure_dialog,null);
                builder2.setView(dialogView2);
                
                builder2.setTitle(R.string.structure_edit_dialog_title);
                //builder2.setIcon(R.drawable.icon);    
                
                final EditText Edit_structureNameEdit = (EditText) dialogView2.findViewById(R.id.editStructureName);     
        		final EditText Edit_structureDescEdit = (EditText) dialogView2.findViewById(R.id.editStructureDescription);
                
                builder2.setPositiveButton(R.string.save,
                		          
                                new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            
                                        	// Defines strings input in by the user
                                            String structureName = Edit_structureNameEdit.getText().toString();
                                            String structureDesc = Edit_structureDescEdit.getText().toString();
                                        	
                                            // Updates the user-defined structure to  the database
                                            //structureID = adapter.getCursor().getInt(adapter.getCursor().getColumnIndex(SqlHelper.COLUMN_ID));
                                            String[][] databaseUpdates = {
                                                    {SqlHelper.COLUMN_STRUCTURE_NAME, structureName},
                                                    {SqlHelper.COLUMN_STRUCTURE_DESC, structureDesc} 
                                                    };
                                            utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID );
                                                                 
                                                                 
                                            // Refersehs the list  view screen with new changes                                              
                                            updateList();
                                            
                                            return;
                                        }
                                });

                builder2.setNegativeButton(android.R.string.cancel,
                                new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {                                                   
                                                return;
                                        }
                                });    
                
                Dialog structureDialogEdit = builder2.create();

                return structureDialogEdit;
        }
            
            
            return null;
                                                  
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {   	
 
        switch (id) { 
            case STRUCTURE_ADD_DIALOG_ID:
                // Clear the input box.
            	final EditText structureNameNew = (EditText) dialog.findViewById(R.id.editStructureName);     
        		final EditText structureDescNew = (EditText) dialog.findViewById(R.id.editStructureDescription);
        		
        		//Clear the EditText fields
        		structureNameNew.setText(""); 
        		structureNameNew.requestFocus();
        		structureDescNew.setText("");
                break;
                
            case STRUCTURE_EDIT_DIALOG_ID:

            	final EditText structureNameEdit = (EditText) dialog.findViewById(R.id.editStructureName);     
        		final EditText structureDescEdit = (EditText) dialog.findViewById(R.id.editStructureDescription);
            	
        		//Clear the EditText fields
        		String oldName = this.currentCursor.getString(this.currentCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NAME));
        		String oldDesc = this.currentCursor.getString(this.currentCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_DESC));
        		
        		structureNameEdit.setText(oldName); 
        		structureNameEdit.requestFocus();
        		structureDescEdit.setText(oldDesc);
                break;            	
                
            default:
            	Log.d(LAYOUT_INFLATER_SERVICE, "Wrong Structure DIALOG ID");
            	break;
        }
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.structure_list_menu, menu);
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
                .getMenuInfo();
     
        structureID = utilsHelper.dbHelper.getStructureID(currentCursor);
        
        switch (item.getItemId()) {
        
	        case R.id.openStructure:
	        	utilsHelper.startNextActivity(structureID,questionnaire_Activity1.class);
	            return true;
	        
	        case R.id.editStructure:
	        	showDialog(STRUCTURE_EDIT_DIALOG_ID);	     
	            return true;
	        
	        case R.id.deleteStructure:
	        	//TODO: Create a "are you sure, prompt"
	        	utilsHelper.dbHelper.delete_byID(structureID);
	        	 updateList();        	
	            return true;
	            
	        case R.id.uploadStructure:
	        	
	        	httpPostHelper httpPost= new httpPostHelper (mContext);
	        	httpPost.postToRemoteDatabase(structureID);

	            return true;
       
        }
        return false;
    }   
    
    private void updateList(){   	
        // Refreshes the list view  to incorporate the newly added/deleted structure
        currentCursor.requery();
        adapter.notifyDataSetChanged();
    }
       
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
            utilsHelper.closeDatabase();
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);
        }
        return super.onKeyDown(keyCode, event);
    }
   
}